package com.example.diancai.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.diancai.util.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createUserId", Integer.class, AuthUtil.getCurrPlayerId());
        this.strictInsertFill(metaObject, "createUserName", String.class, AuthUtil.getCurrNickName());
        this.strictInsertFill(metaObject, "modifyUserId", Integer.class, AuthUtil.getCurrPlayerId());
        this.strictInsertFill(metaObject, "modifyUserName", String.class, AuthUtil.getCurrNickName());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "modifyUserId", Integer.class, AuthUtil.getCurrPlayerId());
        this.strictUpdateFill(metaObject, "modifyUserName", String.class, AuthUtil.getCurrNickName());
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        //如果不是null也填充
        //if (metaObject.getValue(fieldName) == null)
        {
            Object obj = fieldVal.get();
            if (Objects.nonNull(obj)) {
                metaObject.setValue(fieldName, obj);
            }
        }
        return this;
    }
}